package com.myk.game.gobangchess.rooms.oldrooms;

import com.myk.game.gobangchess.DataManager;
import com.myk.game.gobangchess.Sign;
import com.myk.game.gobangchess.rooms.absrooms.AbsMultiViewChessRoom;
import com.myk.game.gobangchess.signs.*;
import com.myk.game.gobangchess.utils.GridsUtils;
// import com.myk.game.gobangchess.CustomBottom;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 双人模式野牛棋（不好玩隐藏了）
 *
 */
public class BuffaloRoom extends AbsMultiViewChessRoom {

    private CacheSign cacheSign;

    public BuffaBloSide side1,side2;
    int handicap=0; //让子功能尚未实现

    int selectingIndex=-1;

    public BuffaloRoom(String roomName) {
        super(roomName, "印第安酋长vs野牛：一款不对称新棋。", "野牛棋", GridsUtils.createEmptyGrids(11, 7), true, true);
        initBoardStyle();
        side1 = new BuffaBloSide(1);
        side2 = new BuffaBloSide(2);
    }

    private void initBoardStyle(){
        List<Sign> boardStyle = new ArrayList<>();
        List<Integer> bGrids = new ArrayList<>();
        List<Integer> wGrids = new ArrayList<>();
        List<Integer> pGrids = new ArrayList<>();
        List<Integer> rGrids = new ArrayList<>();
        for (int i = 0; i < 11; i++) {
            for (int j = 1; j < 6; j++) {
                if ((i + j) % 2 == 0)
                    bGrids.add(getIndex(i, j));
                else
                    wGrids.add(getIndex(i, j));
            }
            if (i % 2 == 0){
                pGrids.add(getIndex(i, 0));
                pGrids.add(getIndex(i, 6));
            }
            else {
                rGrids.add(getIndex(i, 0));
                rGrids.add(getIndex(i, 6));
            }
        }
        boardStyle.add(new ColorSign(bGrids, "#FFC57727"));
        boardStyle.add(new ColorSign(wGrids, "#FF329664"));
        boardStyle.add(new ColorSign(pGrids, "#FFDD6690"));
        boardStyle.add(new ColorSign(rGrids, "#FF9066DD"));
        cacheSign = new CacheSign(this,"background",52,true,boardStyle);
    }

    @Override
    public String getRuleText() {
        return "[玩法]\n" +
                "黑(野牛)先行：选择1枚黑子(野牛)向右移动一格，不可越子、不可吃子。\n" +
                "白(酋长)后行，二选一：\n" +
                "——1. 选择1枚白子(猎犬)按国际象棋的“王后”移动，不可越子、不可吃子；\n" +
                "——2. 将红子(酋长)按国际象棋的“国王”移动，不可越子、可以吃敌子；\n" +
                "白方棋子不可进入棋盘最左侧或者最右侧的列。\n\n" +
                "若黑方将任何一枚棋子移至最右列（即野牛成功入侵村落），则黑方获胜；\n" +
                "若轮到黑方时没有合法行动（即酋长成功防御野牛），则白方获胜。";
    }

    @Override
    public CacheSign getCacheSignByName(String cacheName) {
        return cacheSign;
    }

    @Override
    public Chess getChessByPos(int row, int col) {
        Chess c = side1.getChessByPos(row, col);
        if (c != null) {
                return c;
        }
        c = side2.getChessByPos(row, col);
        return c;
    }

    @Override
    public void removeChess(Chess piece){
        side1.chessList.remove(piece);
        side2.chessList.remove(piece);
    }

    @Override
    public String getGameInfo (int view) {
        //先清空棋盘
        curGrids = GridsUtils.copyGrids(originGrids);
        signList.clear();
        signList.add(cacheSign);
        for (BuffaloRoom.Chess piece :side1.chessList)
            piece.render(this, view);
        for (BuffaloRoom.Chess piece :side2.chessList)
            piece.render(this, view);
        if(selectingIndex!=-1)
            signList.add(new GroundSign(selectingIndex, selectingIndex, "#00000000", "#FFFF3838", 1f, 0, 1)) ;

        //画一下可移动范围
        for (Map.Entry<Integer, String> entry : side1.rangeIndex.entrySet()) {
            signList.add(new TextSign(entry.getKey(),"🐾","#BB000000"));
        }
        side1.clearSign();
        for (Map.Entry<Integer, String> entry : side2.rangeIndex.entrySet()) {
            signList.add(new TextSign(entry.getKey(),"👣","#BB000000"));
        }
        side2.clearSign();

        return "" + step +
                "&" + cur +
                "&" + blackScore +
                "&" + whiteScore +
                "&" + gameTip +
                "&" + GridsUtils.grids2Str(originGrids) + //不绘制棋子
                "&" + getSignsInfo() +
                "&" + getCoordMode();
    }
    @Override
    protected void doStart(){
        DataManager.noticeAllGameStart(player_black, player_white, roomName);
        overFlag = 1;//重置结束状态：对弈进行中未结束
        playingStartTime = System.currentTimeMillis(); //重置对弈开始时间
        resetGrids();
        selectingIndex=-1;
        side1 = new BuffaBloSide(1);
        side2 = new BuffaBloSide(2);
        initPiece();
        noticeFirstMove();
        preHistory();
    }

    @Override
    public void doRule(int row, int col, int value, int view) {
        //if (!modeSelected) {
        //    // 正在选择让子，不要动棋盘
        //    // 让子功能尚未实现
        //    return;
        //}

        selectingIndex=getIndex(row,col);
        BuffaBloSide side;
        if(cur==1) side=side1;
        else side=side2;
        side.selectOrMove(this, row, col);
        //System.out.println("Hoo~");

        if(checkWinBlack())
            doOver(side.mSide, "野牛成功入侵村落！");
        else if(checkWinWhite())
            doOver(side.mSide, "酋长成功防御野牛！");

        getGameInfo();
    }
    public boolean checkWinWhite(){
        if(side1.chessList == null) return true;
        int posx,posy;
        for (Chess chess : side1.chessList){
                posx=chess.pRow; posy=chess.pCol;
                if(posy<6 && this.getChessByPos(posx, posy+1)==null)
                    return false;
        }
        return true;
    }

    public boolean checkWinBlack(){
        for (Chess chess : side1.chessList)
            if(chess.pCol==6)
                return true;
        return false;
    }

    public void noticeFirstMove() {
        if(handicap>=0) noticeBlackMove();
        else noticeWhiteMove();
    }

    public void initSides(){
        sideMap.put(1, new BuffaBloSide(1));
        sideMap.put(2, new BuffaBloSide(1));
    }

    private void initPiece() {
        side1.chessList.add(new BuffaloPiece(1, 0, 0));
        side1.chessList.add(new BuffaloPiece(1, 1, 0));
        side1.chessList.add(new BuffaloPiece(1, 2, 0));
        side1.chessList.add(new BuffaloPiece(1, 3, 0));
        side1.chessList.add(new BuffaloPiece(1, 4, 0));
        side1.chessList.add(new BuffaloPiece(1, 5, 0));
        side1.chessList.add(new BuffaloPiece(1, 6, 0));
        side1.chessList.add(new BuffaloPiece(1, 7, 0));
        side1.chessList.add(new BuffaloPiece(1, 8, 0));
        side1.chessList.add(new BuffaloPiece(1, 9, 0));
        side1.chessList.add(new BuffaloPiece(1, 10, 0));
        side2.chessList.add(new HoundPiece(2, 3, 5));
        side2.chessList.add(new HoundPiece(2, 4, 5));
        side2.chessList.add(new HoundPiece(2, 6, 5));
        side2.chessList.add(new HoundPiece(2, 7, 5));
        side2.chessList.add(new ChiefPiece(2, 5, 5));
    }


    /**
     * 玩家队伍
     */
    public static class BuffaBloSide extends AbsMultiViewChessRoom.Side{

        public BuffaBloSide(int side) {
            super(side);
        }
        public List<Integer> swapRange(AbsMultiViewChessRoom room){ return new ArrayList<>();}
        public boolean canDoEat(AbsMultiViewChessRoom room) {
            return true;
        }
    }

    /**
     * 棋子抽象类
     */
    private static abstract class Pieces extends AbsMultiViewChessRoom.Chess {

        public Pieces(String name, int mSide, int pRow, int pCol) {
            super(name, mSide, pRow, pCol);
        }

        @Override
        public List<Integer> genEatRange(AbsMultiViewChessRoom room, int[][] dxdys, int distance) {
            List<Integer> rangeIndex = new ArrayList<>();
            for (int[] dxdy : dxdys) {
                for (int x = pRow + dxdy[0], y = pCol + dxdy[1], i = 0; x >= 0 && x < room.curGrids.length && y >= 0 && y < room.curGrids[0].length && i < distance; x += dxdy[0], y += dxdy[1], i++) {
                    if(mSide==2 && (y==0 || y==6)) break;  //增加了酋长放不能进入最左侧/最右侧列的要求
                    Chess chess = room.getChessByPos(x, y);
                    if (chess != null)
                        if (chess.mSide != mSide) {
                            rangeIndex.add(room.getIndex(x, y));
                        }else break;
                }}
            return rangeIndex;
        }

        @Override
        public List<Integer> genMoveRange(AbsMultiViewChessRoom room, int[][] dxdys, int distance) {
            List<Integer> rangeIndex = new ArrayList<>();
            for (int[] dxdy : dxdys) {
                for (int x = pRow + dxdy[0], y = pCol + dxdy[1], i = 0; x >= 0 && x < room.curGrids.length && y >= 0 && y < room.curGrids[0].length && i < distance; x += dxdy[0], y += dxdy[1], i++) {
                    if(mSide==2 && (y==0 || y==6)) break;  //增加了酋长放不能进入最左侧/最右侧列的要求
                    Chess chess = room.getChessByPos(x, y);
                    if (chess != null) break;
                    rangeIndex.add(room.getIndex(x, y));
                }}
            return rangeIndex;
        }
    }

    /**
     * 野牛
     */
    private static class BuffaloPiece extends Pieces {
        public BuffaloPiece(int side, int row, int col) {
            super("野牛", side, row, col);
        }

        @Override
        public List<Integer> moveRange(AbsMultiViewChessRoom room) {
            return genMoveRange(room, new int[][]{{0, 1}},1);
        }
        public List<Integer> eatRange(AbsMultiViewChessRoom room) { return new ArrayList<>();}

        @Override
        public void render(AbsMultiViewChessRoom room, int view) {
            room.curGrids[pRow][pCol] = 1;
            room.signList.add(new TextSign(room.getIndex(pRow, pCol), "🐂", getColor()));
        }
    }

    /**
     * 猎犬
     */
    private static class HoundPiece extends Pieces {
        public HoundPiece(int side, int row, int col) {
            super("猎犬", side, row, col);
        }

        public List<Integer> moveRange(AbsMultiViewChessRoom room) {
            return genMoveRange(room, new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1},
                    {1, 1}, {-1, -1}, {-1, 1}, {1, -1}},Integer.MAX_VALUE);
        }
        public List<Integer> eatRange(AbsMultiViewChessRoom room) {
            return new ArrayList<>();
        }

        @Override
        public void render(AbsMultiViewChessRoom room, int view) {
            room.curGrids[pRow][pCol] = 2;
            room.signList.add(new TextSign(room.getIndex(pRow, pCol), "🐕", getColor()));
        }
    }

    /**
     * 酋长
     */
    private static class ChiefPiece extends Pieces {
        public ChiefPiece(int side, int row, int col) {
            super("酋长", side, row, col);
        }

        public List<Integer> moveRange(AbsMultiViewChessRoom room) {
            return genMoveRange(room, new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1},
                    {1, 1}, {-1, -1}, {-1, 1}, {1, -1}},1);
        }
        public List<Integer> eatRange(AbsMultiViewChessRoom room) {
            return genEatRange(room, new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1},
                    {1, 1}, {-1, -1}, {-1, 1}, {1, -1}},1);
        }

        @Override
        public void render(AbsMultiViewChessRoom room, int view) {
            room.curGrids[pRow][pCol] = 3;
            room.signList.add(new TextSign(room.getIndex(pRow, pCol), "💂", getColor()));
        }
    }


}